package com.gyp.controller.video;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.Header;
import com.gyp.dto.user.CreateAnimationTaskDTO;
import com.gyp.entity.GyPayPackage;
import com.gyp.entity.SysJobRecord;
import com.gyp.exception.BusinessException;
import com.gyp.model.common.PageInfo;
import com.gyp.model.common.Result;
import com.gyp.model.common.Search;
import com.gyp.service.GyPayOrderService;
import com.gyp.service.GyPayPackageService;
import com.gyp.service.SysJobRecordService;
import com.gyp.service.VoiceVideoService;
import com.gyp.utils.HttpUtils;
import com.gyp.vo.video.AnimationTaskDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@Validated
@RequiredArgsConstructor
@RequestMapping("/voice/video")
@Slf4j
@Api(tags = "音频驱动相关接口")
public class VoiceController {

    private final VoiceVideoService voiceVideoService;

    private final SysJobRecordService jobRecordService;

    private final GyPayPackageService payPackageService;

    private final GyPayOrderService payOrderService;


    @ApiOperation("创建语音驱动表情动画任务")
    @PostMapping("/animation/task")
    public Result<String> createAnimationTask(@RequestBody @Valid CreateAnimationTaskDTO param) {
        String jobId = voiceVideoService.createAnimationTask(param);
        return Result.data(jobId);
    }

    @SneakyThrows
    @ApiOperation("获取语音驱动表情数据")
    @GetMapping("/animation/task/{id}")
    public void getAnimationTask(@PathVariable("id") String jobId, HttpServletResponse  response) {
        AnimationTaskDetailVO result = voiceVideoService.getAnimationTask(jobId);
        if("SUCCEED".equals(result.getState())){
            byte[] bytes = HttpUtils.requestDownload(result.getFileUrl());
            // 设置响应头
            response.setContentType("application/csv;charset=UTF-8");
            response.setHeader(Header.CONTENT_DISPOSITION.toString(), "attachment;filename=" + URLEncoder.encode("file.csv", "utf-8"));

            // 将文件写入响应输出流
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        }
        else {
            throw new BusinessException("10050","语音数据尚未执行完成");
        }

    }

    @ApiOperation("查看语音驱动任务列表")
    @PostMapping("/job")
    public Result<PageInfo<SysJobRecord>> selectAnimationTaskJobs(@RequestBody Search param) {
        return Result.data(jobRecordService.selectAnimationTaskJobs(param));
    }

    @ApiOperation("充值包列表")
    @PostMapping("/packages")
    public Result<PageInfo<GyPayPackage>> selectPayPackages(Search search){
        return Result.data(payPackageService.selectPayPackages(search));
    }


    @ApiOperation("下载文件")
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile() throws IOException {
        Boolean status = payOrderService.checkOrder();
        if(!status){
            throw new BusinessException("10047");
        }
        ClassPathResource resource = new ClassPathResource("static/deploy.zip");

        byte[] fileContent =  IoUtil.readBytes(resource.getInputStream());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "deploy.zip");
        log.info("下载文件");
        return new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK);
    }

}
